<template>
  <div id="login">
    <transition name="form-fade" mode="in-out">
      <div class="logincontainer">
        <div class="logo-img"></div>
        <div class="input-box">
          <!-- 禁止浏览器记住密码: 1.设置autocomplete属性,禁止自动填充     2.不要设置id和name属性,禁止出现下拉选项 -->
          <el-input
            v-model="param.username"
            class="username"
            placeholder="用户名"
            spellcheck="false"
            autocomplete="off"
          >
            <div class="prefixiconuser" slot="prefix"></div>
          </el-input>
          <el-input
            v-model="param.password"
            style="margin-top:.3rem;"
            class="password"
            spellcheck="false"
            show-password
            placeholder="密码"
            autocomplete="new-password"
          >
            <div class="prefixiconpwd" slot="prefix"></div>
          </el-input>

          <el-row>
            <el-checkbox
              style="margin-top:.2rem;float: left;font-size:.2rem;"
              v-model="remember"
            >记住用户名和密码</el-checkbox>
          </el-row>
          <div class="submitBtn" @click="login()">登录</div>
        </div>
      </div>
    </transition>
    <!--<transition name="form-fade" mode="in-out">
	  				<label>账号</label>
					<input type="text" v-model="param.username"/> <br /><br />
					<label>密码</label>
					<input type="password" v-model="param.password"/> <br /><br />
					<label>验证码</label>
					<input type="text" v-model="param.captcha"/> <br /><br />
					<img class="codeImg" :src="getCodeSrc" @click="changeImg()"/><br /><br />
					<button @click="login()">登录</button>

    </transition>-->
    <crateCampus ref="crateCampus" @callback="closeAdd" @cancel="cancel"></crateCampus>
  </div>
</template>

<script>
import menuTool from "@/js/common/menu";
import setCampusTime from '@/js/common/setCampusTime';
import crateCampus from "./createFirstCampus";

var vm;
export default {
  data: function() {
    return {
      remember: false,
      prefixicon: "../../assets/img/common/login_bg.jpg",
      codeSrc: config.baseUrl + "captcha.jpg?uuid=",
      param: {
        uuid: tool.uuid(),
        username: "",
        password: "",
        captcha: ""
      }
    };
  },
  components: {
    crateCampus
  },
  computed: {
    getCodeSrc: function() {
      return this.codeSrc + this.param.uuid;
    }
  },
  methods: {
    changeImg: function() {
      vm.param.uuid = tool.uuid();
    },
    cancel(data) {
      tool.removeItem(lsKey.token);
    },
    closeAdd(data) {
      vm.login();
    },
    login: function() {
      api
        .login(vm.param)
        .then(function(data) {
          //枚举登录接口返回的情况
          //						var resultMap = {
          //							"账号或密码不正确": "账号或密码有误",
          //							"验证码错误": "验证码有误",
          //							"登录成功": "登录成功",
          //							"账号已被锁定,请联系管理员": "账号已被禁用，请联系管理员"
          //						};
          //						var msg = resultMap[data.result];

          if (data.resultCode != 2000) {
            //提示语,终止请求
            tool.message2({
              showClose: true,
              message: data.message,
              type: "warning"
            });
            return Promise.reject();
          }
          //如果勾选了记住密码,则保持,否则清除
          if (vm.remember) {
            tool.setItem(lsKey.username, vm.param.username);
            tool.setItem(lsKey.password, vm.param.password);
          } else {
            tool.removeItem(lsKey.username);
            tool.removeItem(lsKey.password);
          }

          //获取一些必要数据
          vm.getData();

          //保存token到本地,执行下一个请求
          tool.setItem(lsKey.token, data.token);
          return api.loginUser();
        })
        .then(function(data) {
          //登录验证通过,保存登录用户信息
          tool.setItem(lsKey.user, data.user, true);
          //全局用户角色级别
          vm.$store.commit("setRoleMode", data.user.roleMode); 
          vm.$store.dispatch("top/updateOrgEntrySchool", false);
          if(data.user.isAttaching=='1'){
            vm.$store.dispatch("top/updateOrgEntrySchool", true);
          }

          //选择机构
          data.user.orgList = data.user.orgList || [];
          if(data.user.roleMode != 0 && data.user.orgList.length > 1)
          {
            router.push('/selectOrg');
            return Promise.reject();
          }

          //用户有关联校区
          if (data.user.campusList.length > 0) {
            //获取本校区上课时间
            let param = {
              campusId: data.user.campusList[0].campusId
            };
            api.getListOfCampus(param).then(function(data) {
              setCampusTime(data.list);
            });
            //默认用户所属校区的第一个为当前校区,保存校区id至状态管理
            vm.$store.commit("setCampusId", data.user.campusList[0].campusId);

            return api.menu();
          }

          //用户无关联校区,各个角色对应的处理
          if (data.user.roleMode == 0) {
            //平台管理员
            return api.menu();
          } else if (data.user.roleMode == 1) {
            console.log(data.user);
            if (data.user.childRoleMode == null) {
              //机构管理员
              tool.message2({
                showClose: true,
                message: "该账号关联的机构暂无校区，请新增校区",
                type: "warning"
              });
              vm.$refs.crateCampus.init({});
            } else {
              //督导级角色用户
              tool.removeItem(lsKey.token);
              tool.message2({
                showClose: true,
                message: "该账号所管辖范围没有校区，请联系管理员",
                type: "warning"
              });
            }

            return Promise.reject();
          } else {
            //其他角色:校区管理员,普通角色...
            //清除token,就当没登录
            tool.removeItem(lsKey.token);
            tool.message2({
              showClose: true,
              message: "该账号没有关联校区,请联系管理员",
              type: "warning"
            });
            return Promise.reject();
          }
        })
        .then(function(data) {
          //根据菜单设置路由,获取权限数据
          var permit = menuTool.getPermit(data.menuList);
          vm.$store.commit("setPermit", permit);

          //根据菜单获取导航数据
          var navObj = menuTool.getNav(data.menuList);
          vm.$store.commit("setNav", navObj.nav);
          vm.$store.commit("setFirstPath", navObj.firstPath);

          //首个路径
          var path = navObj.firstPath;
          if (path) {
            router.push(path);
          }
        })
        .catch(function() {});
    },
    getData: function() {
      api.dictAll({}).then(function(data) {
        var dict = {};
        data.list.forEach(function(item) {
          //根据字典key值保存对应数组
          var key = item.dicKey;
          if (!dict[key]) {
            dict[key] = [];
          }
          dict[key].push({
            name: item.name,
            value: item.dicValue
          });
        });
        //保存到缓存
        tool.setItem(lsKey.dict, dict, true);
      });

      api.getSTSToken().then(function(data) {
        //保存到缓存
        tool.setItem(lsKey.stsToken, data.info, true);
      });
    }
  },
  mounted: function() {
    //账号密码输入框监听回车键事件
    $(".username,.password").bind("keyup", function(event) {
      if (event.keyCode == "13") {
        vm.login();
      }
    });

    //从缓存中获取账号密码
    vm.param.username = tool.getItem(lsKey.username) || "";
    vm.param.password = tool.getItem(lsKey.password) || "";
    //如果有的话,则默认勾上记住密码
    if (vm.param.username) {
      vm.remember = true;
    }
  },
  created: function() {
    vm = this;
    //设置顶部图标
    $("#link_icon").attr("href", "./static/img/logo.png");
  }
};
</script>

<style lang="scss">
#login {
  padding-top: 0.5rem;
  text-align: center;
  width: 100%;
  height: 100%;
  background: url(../../assets/img/common/login_bg.jpg);
  background-size: cover;
  .el-input--prefix .el-input__inner {
    height: 0.45rem;
    font-size: 0.15rem;
    padding-left: 0.4rem;
  }
}

.codeImg {
  height: 0.35rem;
}

.logincontainer {
  width: 5rem;
  height: 4rem;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -2.5rem;
  margin-top: -2rem;
  background: #ffffff;
  border-radius: 0.1rem;
  box-shadow: 0.01rem 0.01rem 0.01rem 0.01rem #81b4c7;
}

.logo-img {
  width: 3.03rem;
  height: 1.01rem;
  background: url(../../assets/img/common/login_logo.png);
  background-size: 90%;
  background-repeat: no-repeat;
  background-position: center;
  margin: 0.1rem auto;
}

.input-box {
  width: 100%;
  height: 3.5rem;
  padding: 0 0.5rem 0 0.5rem;
}

.prefixiconuser {
  width: 0.23rem;
  height: 0.24rem;
  margin-top: 0.1rem;
  margin-left: 0.05rem;
  background: red;
  background: url(../../assets/img/common/User.png);
  background-size: 0.23rem 0.24rem;
}

.prefixiconpwd {
  width: 0.23rem;
  height: 0.24rem;
  margin-top: 0.1rem;
  margin-left: 0.05rem;
  background: red;
  background: url(../../assets/img/common/Key.png);
  background-size: 0.23rem 0.24rem;
}

.submitBtn {
  width: 100%;
  height: 0.5rem;
  margin-top: 0.3rem;
  background: #3887fe;
  color: #ffffff;
  text-align: center;
  line-height: 0.5rem;
  font-size: 0.25rem;
  cursor: pointer;
}
</style>